package drongo.desktop.cmd
{
	/**
	 * CMD命令单元，包含一个命令格式检测对象，用来检测输入的命令是否满足自身格式
	 * </p>检测规则：首先检测主命令是否满足，如果满足则进行拓展命令的检测，拓展命令检测失败则整个命令检测失败
	 * @author Grayness
	 */	
	public class CMDItem
	{
		//主命令格式检测对象
		public var mainCMDFormat:CMDFormat;
		//拓展命令格式检测对象列表
		public var extensCMDFormatList:Vector.<CMDFormat>;
		//命令参数回调序列
		public var insertOrder:Array;
		//回调方法
		public var work:Function;
		public function CMDItem(mainCMDFormatStr:String,extendsCMDFormatStrList:Array,insertOrder:Array,work:Function)
		{
			mainCMDFormat=CMDFormat.createWithCMDFormatString(mainCMDFormatStr);
			extensCMDFormatList=new Vector.<CMDFormat>();
			for each(var str:String in extendsCMDFormatStrList)
			{
				extensCMDFormatList.push(CMDFormat.createWithCMDFormatString(str));
			}
			this.insertOrder=insertOrder;
			this.work=work;
		}
		/**
		 *通过自身的格式列表来检测一组输入是否匹配，如果检测成功可直接调用run方法执行对应回调，请不要在检测不成功的情况下调用run，否者会出现错误
		 */		
		public function check(cmds:Vector.<CMDValue>):Boolean
		{
			if(cmds.length==0)
				return false;
			if(mainCMDFormat.check(cmds[0]))//主命令检测
			{
				var arr:Array=[];
				arr=arr.concat(mainCMDFormat.usefulArgument);
//				var find:Boolean=false;
				for(var i:int=1;i<cmds.length;i++)
				{
//					find=false;
					b:for each(var format:CMDFormat in extensCMDFormatList)
					{
						if(cmds[i].cmdName==format.cmdName&&format.check(cmds[i]))
						{
//							find=true;
							break b;
						}
					}
//					if(!find)
//						return false;
				}
				return true;
			}
			return false;
		}
		/**
		 *执行命令 
		 * @param cmds
		 */		
		public function run():void
		{
			trace(mainCMDFormat.cmdName);
			if(work!=null)
			{
				var tmplist:Vector.<CMDFormat>=extensCMDFormatList.concat();
				tmplist.push(mainCMDFormat);
				var argu:Array=[];
				for each (var cmdName:String in insertOrder)
				{
					for each(var format:CMDFormat in tmplist)
					{
						if(format.cmdName==cmdName)
							argu=argu.concat(format.usefulArgument);
					}
				}
				work.apply(this,argu);
			}
		}
	}
}
